package com.zmx.user.web;

import com.zmx.common.common.utils.VerifyCodeUtil;
import com.zmx.common.common.web.rest.ResponseResult;
import com.zmx.user.dto.LoginParameterDto;
import com.zmx.user.service.SysLoginService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;


/**
 * @Description: 用户登录控制器
 * @ClassName: LoginController
 * @Author zhaomxr
 * @Date 2021-11-09 11:19
 */
@Slf4j
@RestController
public class SysLoginController {

    @Autowired
    private SysLoginService sysLoginService;

    /**
     * 登录
     *
     * @param loginParameterDto 登录信息
     */
    @PostMapping("syslogin")
    public ResponseResult<Map> login(@RequestBody LoginParameterDto loginParameterDto, HttpServletRequest request) {
        log.info("开始登录 用户信息：{}", loginParameterDto);
        return sysLoginService.login(loginParameterDto,request);
    }

    /**
     * 获取图片验证码
     * @param request
     * @param response
     */
    @GetMapping("/syslogin/verifyCode")
    public void getVerifyCode(HttpServletRequest request, HttpServletResponse response) {

        OutputStream os = null;
        try {

            int width = 200;
            int height = 69;

            BufferedImage verifyImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            //生成对应宽高的初始图片
            String randomText = VerifyCodeUtil.getCode(width, height, verifyImg);
            //功能是生成验证码字符并加上噪点，干扰线，返回值为验证码字符
            request.getSession().setAttribute("verifyCode", randomText);

            //必须设置响应内容类型为图片，否则前台不识别
            response.setContentType("image/png");
            //获取文件输出流
            os = response.getOutputStream();
            //输出图片流
            ImageIO.write(verifyImg, "png", os);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                os.flush();
                os.close();//关闭流
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 刷新图片验证码
     * @param request
     * @param response
     */
    @GetMapping("/syslogin/refreshVerifyCode")
    public void refreshVerifyCode(HttpServletRequest request, HttpServletResponse response) {
        this.getVerifyCode(request, response);
    }

    /**
     * 登出
     *
     * @return
     */
    @PostMapping("/syslogin/login-out")
    public void loginOut() {
        sysLoginService.loginOut();
    }
}

